#include "BlockQueue.hpp"
#include "Thread.hpp"
#include "Task.hpp"
#include <string>
#include <vector>
#include <unistd.h>

using namespace std;
using namespace ThreadModule;

int a = 10;

using blockqueue_t = BlockQueue<Task>;

void Consumer(blockqueue_t &bq)
{
    while (true)
    {
        //从blockqueue中取得任务
        Task t;
        bq.Pop(&t);
        //处理这个任务
        t.result();
        cout<<"消费者："<<t.ToString()<<endl;
    }
}

void Productor(blockqueue_t &bq)
{
    srand(time(nullptr)^pthread_self());
    while (true)
    {
        sleep(1);
        //1.获取任务
        int a=rand()%10+1;
        usleep(1000);
        int b=rand()%10+1;
        Task t(a,b);
        //2.将获取的renw，放入blockqueue中
        bq.Enqueue(t);
        cout << "生产者：" <<t.DebugToString()<< endl;
    }
}

void Start(vector<Thread<blockqueue_t>> *threads, int num, blockqueue_t &bq, func_t<blockqueue_t> func)
{
    for (int i = 0; i < num; i++)
    {
        // Thread(func_t<T> func, T &data, const std::string &name="none-name")
        string name = "Thread-" + to_string(i + 1);
        threads->emplace_back(func, bq, name);
        threads->back().Start();
    }
}

void StartConsumer(vector<Thread<blockqueue_t>> *threads, int num, blockqueue_t &bq)
{
    Start(threads, num, bq, Consumer);
}
void StartProductor(vector<Thread<blockqueue_t>> *threads, int num, blockqueue_t &bq)
{
    Start(threads, num, bq, Productor);
}

void WaitAllThread(vector<Thread<blockqueue_t>> &threads)
{
    for (auto &thread : threads)
    {
        thread.Join();
    }
}
int main()
{
    blockqueue_t *bq = new blockqueue_t(5);
    vector<Thread<blockqueue_t>> threads;
    // 启动线程
    StartConsumer(&threads, 3, *bq);
    StartProductor(&threads, 1, *bq);
    // 等待所有线程
    WaitAllThread(threads);

    return 0;
}